import React from 'react';
import { Table, Button, Space, Tooltip } from 'antd';
import styled from '@emotion/styled';
import { useTranslation } from 'react-i18next';
import SearchHeader from './SearchHeader';
import moment from 'moment';
import { getSessionRecordList, getSessionSummary, exportSessionList } from '@/api/index';
import Message from '@/utils/message';
import type { TablePaginationConfig } from 'antd/es/table';
import useSyncState from '../hooks/useSyncState';
import SummaryForm from '../SessionSummary/SummaryForm';
import AgentService from '@/modules/Agent';
import dayjs from 'dayjs';
import FileSaver from 'file-saver';

const TableWrapper = styled.div`
	overflow: auto;
	font-size: 13px;

	table {
		white-space: nowrap;
		font-size: 13px;
	}
`;

const ButtonSpan = styled.span`
	cursor: pointer;
	color: #1890ff;
`;

const WrapSpan = styled.span`
	white-space: pre-wrap;
`;

const ButtonItem = styled(Button)`
	position: relative;
`;
const MenuDot = styled.span`
	background: #f00;
	display: inline-block;
	width: 10px;
	height: 10px;
	position: absolute;
	border-radius: 50%;
	z-index: 1;
	left: 48px;
	top: -5px;
`;

const ServiceRecord = () => {
	const { t } = useTranslation();

	const [recordData, setRecordData] = React.useState([]);
	const [pagination, setPagination] = React.useState<TablePaginationConfig>({
		current: 1,
		pageSize: 10,
		total: 0,
		showSizeChanger: true,
		showQuickJumper: true
		// showTotal: total => `共 ${total} 条`
	});
	const [condition, setCondition] = useSyncState<any>({ sesionId: '', isAccepted: -1, isConnect: -1, scenarioName: '', acceptedTime: [], curRate: 0 });
	const [summaryData, setSummaryData] = useSyncState<any>({});
	const [showSummaryForm, setShowSummaryForm] = React.useState<boolean>(false);
	const [summaryFormType, setSummaryFormType] = React.useState<string>('');
	const [curRecord, setCurRecord] = React.useState<any>({});

	React.useEffect(() => {
		fetchRecords();
	}, [pagination.pageSize]);

	React.useEffect(() => {
		fetchRecords();
	}, [pagination.current]);

	// sessions 页面人工坐席筛选
	const filterAgent = (agnetParams: any) => {
		let agent: any = [];
		agnetParams.forEach((item: any) => {
			if (!item.isRobot) {
				if (item.assignedAgentId && !agent.includes(item.assignedAgentId)) {
					agent.push(item.assignedAgentId);
				}
			}
		});
		return agent.join(';') || '-';
	};

	// sessions 页面机器人坐席筛选
	const filterAiAgent = (agnetParams: any) => {
		let aiAgent: any = [];
		agnetParams.forEach((item: any) => {
			if (item.isRobot) {
				if (item.assignedAgentId && !aiAgent.includes(item.assignedAgentId)) {
					aiAgent.push(item.assignedAgentId);
				}
			}
		});
		return aiAgent.join(';') || '-';
	};

	const getFailReasonStatus = (status: string) => {
		let result = '';
		switch (status) {
			case 'canceled':
				result = '访客取消呼叫';
				break;
			case 'notfound':
				result = '未找到坐席'; //(没有找到在线的，并且签入了业务场景对应的坐席)
				break;
			case 'timeout':
				result = '呼叫超时';
				break;
			case 'offday':
				result = '不在工作日';
				break;
			case 'offtime':
				result = '不在工作时间';
				break;
			case 'scenariodisabled':
				result = '业务场景未启用';
				break;
			case 'otherCustomerAccept':
				result = '其他坐席已经接听';
				break;
			case 'multiCustomerForbidAI':
				result = '指定机器人呼叫时会话中存在多访客';
				break;
			case 'rejected':
				result = '坐席拒绝';
				break;
			case 'ringingTimeout':
				result = '振铃超时';
				break;
			case 'customerRolesEmpty':
				result = '访客角色为空';
				break;
			case 'scenarioRolesEmpty':
				result = '呼叫的业务场景角色为空';
				break;
			case 'scenarioRolesNotMatched':
				result = ' 业务场景角色不匹配';
				break;
			case 'ban':
				result = '命中黑名单';
				break;
			default:
				result = '-';
				break;
		}
		return result;
	};

	// 未提交、非常满意、满意、一般、不满意、非常不满意
	const getRateText = (rate: number) => {
		if (rate === 1) {
			return '非常不满意';
		} else if (rate === 2) {
			return '不满意';
		} else if (rate === 3) {
			return '一般';
		} else if (rate === 4) {
			return '满意';
		} else if (rate === 5) {
			return '非常满意';
		} else {
			return '未提交';
		}
	};

	const fetchRecords = async () => {
		const { current, pageSize } = pagination;
		const { sesionId, isAccepted, isConnect, scenarioName, acceptedTime = [], curRate, summaryIsCompleted } = condition();
		const param = {
			page: current,
			pageSize: pageSize,
			sessionId: sesionId,
			acceptedStartTime: acceptedTime[0] ? moment(acceptedTime[0]).format('YYYY-MM-DD HH:mm:ss') : '',
			acceptedEndTime: acceptedTime[1] ? moment(acceptedTime[1]).format('YYYY-MM-DD HH:mm:ss') : '',
			isAccepted: isAccepted === -1 ? '' : isAccepted === 1 ? true : false,
			isConnected: isConnect === -1 ? '' : isConnect === 1 ? true : false,
			scenarioName: scenarioName,
			score: curRate === 0 ? '' : curRate
		};
		try {
			const { data } = await getSessionRecordList(param);
			console.log('fetchRecords', data);
			if (data.code === 200) {
				const { total } = data.data;
				setPagination({ ...pagination, total: total });
				data.data.data.map((item: any) => {
					item.startDialingTime = item.createdAt ? moment(item.createdAt).format('YYYY-MM-DD HH:mm:ss') : '-';
					item.acceptedTime = item.acceptedAt ? moment(item.acceptedAt).format('YYYY-MM-DD HH:mm:ss') : '-';
					item.hangUpTime = item.closedAt ? moment(item.closedAt).format('YYYY-MM-DD HH:mm:ss') : '-';
					item.isAccepted = item.status === 'accepted' ? '是' : '否';
					item.isConnect = item.media === 'im' ? (item.acceptedAt ? '是' : '否') : item.audioVideoCallIsConnected === '1' ? '是' : '否';
					item.agentId = filterAgent(item.assignedAgents);
					item.aiAgentId = filterAiAgent(item.assignedAgents);
					item.scenarioName = item.toScenarioName || '-';
					item.failReason = getFailReasonStatus(item.failReason);
					item.rate = getRateText(item.score);
					item.summaryIsCompleted = item.summaryIsCompleted;
					item.leavingMessage = item.suggestion || '-';
				});
				setRecordData(data.data.data || []);
			} else {
				Message.warning(t('failed-get-service-record'));
			}
		} catch (error) {
			console.log('fetchRecords error', error);
			Message.warning(t('failed-get-service-record'));
		}
	};

	const handleSearch = (data: any) => {
		console.log('condition', data);
		setCondition(data);
		if (pagination.current === 1) {
			fetchRecords();
		} else {
			setPagination({ ...pagination, current: 1 });
		}
	};

	const handleSummaryEdit = (event: any, record: any) => {
		event.preventDefault();
		event.stopPropagation();
		console.log('edit', record);
		setSummaryFormType('edit');
		setCurRecord(record);
		setShowSummaryForm(true);
	};

	const handleSummaryView = (record: any) => {
		console.log('view', record);
		setSummaryFormType('view');
		setCurRecord(record);
		setShowSummaryForm(true);
	};

	const columns = [
		{
			title: '会话ID',
			dataIndex: 'sessionId',
			key: 'sessionId',
			width: '10%'
		},
		{
			title: 'AI坐席工号',
			dataIndex: 'aiAgentId',
			key: 'aiAgentId',
			width: '5%'
		},
		{
			title: '人工坐席工号',
			dataIndex: 'agentId',
			key: 'agentId',
			width: '10%'
		},
		{
			title: '是否接听',
			dataIndex: 'isAccepted',
			key: 'isAccepted',
			width: '5%'
		},
		{
			title: '是否接通',
			dataIndex: 'isConnect',
			key: 'isConnect',
			width: '5%'
		},
		{
			title: '业务场景',
			dataIndex: 'scenarioName',
			key: 'scenarioName',
			width: '10%',
			ellipsis: true
		},
		{
			title: '拨号开始时间',
			dataIndex: 'startDialingTime',
			key: 'startDialingTime',
			width: '10%'
		},
		{
			title: '通话开始时间',
			dataIndex: 'acceptedTime',
			key: 'acceptedTime',
			width: '10%'
		},
		{
			title: '通话结束时间',
			dataIndex: 'hangUpTime',
			key: 'hangUpTime',
			width: '10%'
		},
		{
			title: '会话建立失败原因',
			dataIndex: 'failReason',
			key: 'failReason',
			width: '10%',
			ellipsis: true
		},
		{
			title: '会话小结',
			dataIndex: 'summary',
			key: 'summary',
			width: '10%',
			render: (_: any, record: any) =>
				record.isSummaryOn === 'Y' && record.isConnect === '是' && AgentService.sessionId !== record.sessionId ? (
					<Space size="middle" style={{ position: 'relative' }}>
						<ButtonItem type="primary" size="small" onClick={e => handleSummaryEdit(e, record)}>
							编辑
						</ButtonItem>
						<ButtonItem type="primary" size="small" onClick={() => handleSummaryView(record)}>
							查看
						</ButtonItem>
						{record.summaryIsCompleted !== 'Y' && <MenuDot />}
					</Space>
				) : (
					'-'
				)
		},
		{
			title: '评价',
			dataIndex: 'rate',
			key: 'rate',
			width: '5%'
		},
		{
			title: '评价内容',
			dataIndex: 'leavingMessage',
			key: 'leavingMessage',
			width: '10%',
			ellipsis: {
				showTitle: false
			},
			render: (_: any, record: any) => (
				<Tooltip placement="topLeft" title={record.leavingMessage}>
					{record.leavingMessage}
				</Tooltip>
			)
		}
	];

	const handleTableChange = (page: TablePaginationConfig) => {
		setPagination(page);
	};

	const handleReset = () => {
		setCondition({ isAccepted: -1, isConnect: -1, scenarioName: '', acceptedTime: [], curRate: 0 });
		setRecordData([]);
		fetchRecords();
	};

	const handleSummarySave = async () => {
		setShowSummaryForm(false);
		const record: any = recordData.find((item: any) => item.id === curRecord.id);
		if (record) {
			record.summaryIsCompleted = 'Y';
			setRecordData([...recordData]);
		}
		setTimeout(() => {
			AgentService.getUnfinishedSummary();
		}, 1000);
	};

	const exportFile = async (data: any) => {
		console.log('exportFile', data);
		setCondition(data);
		const { sesionId, isAccepted, isConnect, scenarioName, acceptedTime = [], curRate } = condition();
		const param = {
			sessionId: sesionId,
			acceptedStartTime: acceptedTime[0] ? moment(acceptedTime[0]).format('YYYY-MM-DD HH:mm:ss') : '',
			acceptedEndTime: acceptedTime[1] ? moment(acceptedTime[1]).format('YYYY-MM-DD HH:mm:ss') : '',
			isAccepted: isAccepted === -1 ? '' : isAccepted === 1 ? true : false,
			isConnected: isConnect === -1 ? '' : isConnect === 1 ? true : false,
			scenarioName: scenarioName,
			score: curRate === 0 ? '' : curRate
		};

		try {
			const data = await exportSessionList(param as any);
			if (data.data) {
				const xlsx = new Blob([data.data]);
				FileSaver.saveAs(xlsx, `${new Date().getFullYear() + '年' + (new Date().getMonth() + 1) + '月' + new Date().getDate() + '日'}` + '.xlsx');
				// message.success('服务记录下载成功');
			}
		} catch (error) {
			Message.warning('服务记录下载失败');
		}
	};

	return (
		<>
			<SearchHeader onSearch={handleSearch} onReset={handleReset} exportFile={exportFile} />
			<TableWrapper>
				<Table columns={columns} dataSource={recordData} rowKey="sessionId" bordered size="middle" scroll={{ x: '120vw' }} pagination={pagination} onChange={handleTableChange} />
			</TableWrapper>
			{showSummaryForm && (
				<SummaryForm
					type={summaryFormType}
					sessionId={curRecord.sessionId}
					sceneId={curRecord.toScenarioId}
					onClose={() => setShowSummaryForm(false)}
					onSave={handleSummarySave}
					isNotice={false}
				/>
			)}
		</>
	);
};

export default ServiceRecord;
